from rest_framework import serializers
from .models import (
    ZabbixServer, MonitoringHost, MonitoringAlert,
    AlertRule, NotificationChannel, AlertNotification, HostGroup, EmailConfig
)
from cmdb.models import Host


class ZabbixServerSerializer(serializers.ModelSerializer):
    """Zabbix服务器序列化器"""
    connection_status_display = serializers.CharField(source='get_connection_status_display', read_only=True)
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = ZabbixServer
        fields = [
            'id', 'name', 'description', 'url', 'username', 'password', 'api_token',
            'is_active', 'is_default', 'connection_status', 'connection_status_display',
            'last_check_time', 'error_message', 'total_hosts', 'total_items', 'total_triggers',
            'created_at', 'updated_at', 'created_by', 'created_by_name'
        ]
        extra_kwargs = {
            'password': {'write_only': True},
            'api_token': {'write_only': True},
        }


class ZabbixServerCreateSerializer(serializers.ModelSerializer):
    """Zabbix服务器创建序列化器"""

    class Meta:
        model = ZabbixServer
        fields = [
            'name', 'description', 'url', 'username', 'password', 'api_token',
            'is_active', 'is_default'
        ]
        extra_kwargs = {
            'password': {'write_only': True},
            'api_token': {'write_only': True},
        }


# GrafanaServer序列化器已移除，使用Zabbix原生仪表板功能


class MonitoringHostSerializer(serializers.ModelSerializer):
    """监控主机序列化器"""
    host_info = serializers.SerializerMethodField()
    zabbix_server_name = serializers.CharField(source='zabbix_server.name', read_only=True)
    monitoring_status_display = serializers.CharField(source='get_monitoring_status_display', read_only=True)

    class Meta:
        model = MonitoringHost
        fields = [
            'id', 'host', 'host_info', 'zabbix_server', 'zabbix_server_name',
            'zabbix_host_id', 'zabbix_host_name', 'monitoring_status', 'monitoring_status_display',
            'applied_templates', 'last_check_time', 'availability', 'error_message',
            'total_items', 'total_triggers', 'active_alerts',
            'created_at', 'updated_at'
        ]

    def get_host_info(self, obj):
        """获取主机基本信息"""
        return {
            'id': obj.host.id,
            'hostname': obj.host.hostname,
            'private_ip': obj.host.private_ip,
            'public_ip': obj.host.public_ip,
            'status': obj.host.status,
        }


class MonitoringAlertSerializer(serializers.ModelSerializer):
    """监控告警序列化器"""
    host_info = serializers.SerializerMethodField()
    zabbix_server_name = serializers.SerializerMethodField()
    severity_display = serializers.CharField(source='get_severity_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    acknowledged_by_name = serializers.SerializerMethodField()

    class Meta:
        model = MonitoringAlert
        fields = [
            'id', 'title', 'description', 'host_info', 'zabbix_server_name',
            'zabbix_event_id', 'zabbix_trigger_id', 'severity', 'severity_display',
            'status', 'status_display', 'event_time', 'acknowledged_time', 'resolved_time',
            'acknowledged_by_name', 'acknowledgment_message', 'raw_data',
            'created_at', 'updated_at'
        ]

    def get_host_info(self, obj):
        """获取主机基本信息"""
        if hasattr(obj, 'host') and obj.host_id:
            try:
                host = obj.host
                return {
                    'id': host.id,
                    'hostname': host.hostname,
                    'private_ip': host.private_ip,
                    'public_ip': host.public_ip,
                }
            except:
                pass

        return {
            'id': None,
            'hostname': '未知主机',
            'private_ip': None,
            'public_ip': None,
        }

    def get_acknowledged_by_name(self, obj):
        """获取确认人用户名"""
        return obj.acknowledged_by.username if obj.acknowledged_by else None

    def get_zabbix_server_name(self, obj):
        """获取Zabbix服务器名称"""
        return obj.zabbix_server.name if obj.zabbix_server else None


class AlertRuleSerializer(serializers.ModelSerializer):
    """告警规则序列化器"""
    zabbix_server_name = serializers.CharField(source='zabbix_server.name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    severity_display = serializers.CharField(source='get_severity_display', read_only=True)
    condition_display = serializers.CharField(source='get_condition_display', read_only=True)

    class Meta:
        model = AlertRule
        fields = '__all__'


class NotificationChannelSerializer(serializers.ModelSerializer):
    """通知渠道序列化器"""
    channel_type_display = serializers.CharField(source='get_channel_type_display', read_only=True)

    class Meta:
        model = NotificationChannel
        fields = '__all__'


class AlertNotificationSerializer(serializers.ModelSerializer):
    """告警通知序列化器"""
    alert_title = serializers.CharField(source='alert.title', read_only=True)
    channel_name = serializers.CharField(source='channel.name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = AlertNotification
        fields = '__all__'


class HostGroupSerializer(serializers.ModelSerializer):
    """主机组序列化器"""
    zabbix_server_name = serializers.CharField(source='zabbix_server.name', read_only=True)

    class Meta:
        model = HostGroup
        fields = '__all__'


class EmailConfigSerializer(serializers.ModelSerializer):
    """邮件配置序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = EmailConfig
        fields = [
            'id', 'name', 'smtp_server', 'smtp_port', 'username', 'password',
            'from_email', 'default_recipients', 'use_tls', 'use_ssl', 'is_default', 'is_active',
            'created_by', 'created_by_name', 'created_at', 'updated_at'
        ]
        extra_kwargs = {
            'password': {'write_only': True, 'required': False},
            'created_by': {'read_only': True},
        }

    def update(self, instance, validated_data):
        """更新邮件配置，正确处理密码字段"""
        # 如果密码字段为空或未提供，则不更新密码
        password = validated_data.pop('password', None)

        # 更新其他字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        # 只有在提供了密码时才更新密码
        if password:
            instance.password = password

        instance.save()
        return instance
